/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.client.event;

import io.iec.edp.caf.commons.event.StartupCompletedEvent;
import io.iec.edp.caf.commons.utils.InvokeService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.msu.common.manager.AppManager;
import io.iec.edp.caf.multicontext.context.PlatformApplicationContext;
import io.iec.edp.caf.multicontext.support.ModuleManager;
import io.iec.edp.caf.rpc.RpcServiceRegister;
import io.iec.edp.caf.rpc.api.annotation.GspServiceBundle;
import io.iec.edp.caf.rpc.client.loader.RpcServicePreload;
import io.iec.edp.caf.rpc.client.loader.RpcServiceRegistryStarter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.util.Set;

/**
 * @author wangyandong
 */
@Order(value = Ordered.HIGHEST_PRECEDENCE + 1)
@Slf4j
public class RpcStartupCompletedListener implements ApplicationListener<StartupCompletedEvent> {

    private Boolean rpcRegistryEnable;

    public RpcStartupCompletedListener(Boolean rpcRegistryEnable) {
        this.rpcRegistryEnable = rpcRegistryEnable;
    }

    @Override
    public void onApplicationEvent(StartupCompletedEvent myEvent) {
        //懒加载模式下，把Rpc的RESTEndpoint注册一下
        //todo 目前caf自己的都没用懒加载了，这块是不是可以注释掉了
//        CAFServerConfigurationProperties properties =
//                SpringBeanUtils.getBean(CAFServerConfigurationProperties.class);
//        if (properties != null && properties.isLazyInitialization()) {
//            RESTEndpoint endpoint = SpringBeanUtils.getBean("rpcServerRest", RESTEndpoint.class);
//            RESTEndpointRegistrar registrar = SpringBeanUtils.getBean(RESTEndpointRegistrar.class);
//            registrar.register(endpoint, endpoint.getPath());
//        }

        //获取所有RPCInterface
        Set<Class<?>> rpcInterfaces = getRpcInterfaces();
        //获取外部通过接口注册进来的
        RpcServiceRegister rpcServiceRegister = RpcServiceRegister.getSingleton();
        rpcInterfaces.addAll(rpcServiceRegister.getRpcInterfaces());
        rpcServiceRegister.finishRegistry();

        //注册内部服务
        RpcServiceRegistryStarter.registerRpcService(rpcInterfaces);
    }

    private Set<Class<?>> getRpcInterfaces() {
        Set<Class<?>> result = AppManager.getClassesWithAnnotation(GspServiceBundle.class);
        //获取模块内的Rpc服务列表
        ApplicationContext ctx = SpringBeanUtils.getApplicationContext();
        if (ctx instanceof PlatformApplicationContext) {
            ModuleManager moduleManager = ((PlatformApplicationContext) ctx).getModuleManager();
            result.addAll(moduleManager.getClassesWithAnnotation(GspServiceBundle.class));
        }

        for (String name : RpcServicePreload.SYS_RPC_LIST) {
            Class c = null;
            try {
                c = InvokeService.getClass(name);
            } catch (RuntimeException e) {
                log.warn("Interface: " + name + " not found in sys dir.");
            }

            if (c != null && c.getAnnotation(GspServiceBundle.class) != null) {
                result.add(c);
            }
        }

        return result;
    }
}
